package com.workflow.sdk.domain.service;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @description: 动态替换表名拦截器
 * @author: cyj
 * @created: 2022/8/1
 */
//method = "query"拦截select方法、而method = "update"则能拦截insert、update、delete的方法
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Slf4j
@Component
public class ReplaceTableInterceptor implements Interceptor {

    private final static InheritableThreadLocal<String> TARGET_TABLE_NAME = new InheritableThreadLocal();

    protected static String getTargetTableName() {
        return TARGET_TABLE_NAME.get();
    }

    protected static void setTargetTableName(String targetTableName) {
        TARGET_TABLE_NAME.set(targetTableName);
    }

    protected static void removeTargetTableName() {
        TARGET_TABLE_NAME.remove();
    }


    /**
     * 通用表名称
     */
    private final static String TABLE_NAME = "t_workflow_execute";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
//        StopWatch stopWatch = new StopWatch();
//        stopWatch.start();
        // 不需要篡改表 直接返回
        if (StringUtils.isNotEmpty(getTargetTableName())) {
            Object[] args = invocation.getArgs();
            //获取MappedStatement对象
            MappedStatement ms = (MappedStatement) args[0];
            //获取传入sql语句的参数对象
            Object parameterObject = args[1];

            BoundSql boundSql = ms.getBoundSql(parameterObject);
            //获取到拥有占位符的sql语句
            String sql = boundSql.getSql();
            // 直接执行
            if (sql.contains(TABLE_NAME)) {

                log.info("替换前sql : {}", sql);

                //重新生成一个BoundSql对象
                BoundSql bs = new BoundSql(ms.getConfiguration(), sql.replaceAll(TABLE_NAME, getTargetTableName()), boundSql.getParameterMappings(), parameterObject);
                log.info("替换后sql : {}", bs.getSql());
                //重新生成一个MappedStatement对象
                MappedStatement newMs = copyMappedStatement(ms, new BoundSqlSqlSource(bs));

                //赋回给实际执行方法所需的参数中
                args[0] = newMs;

            }
        }

        //stopWatch.stop();
        //log.info("执行ReplaceTableInterceptor 耗时：{} ms", stopWatch.getTotalTimeMillis());

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }

    /***
     * 复制一个新的MappedStatement
     * @param ms
     * @param newSqlSource
     * @return
     */
    private MappedStatement copyMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());

        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(String.join(",", ms.getKeyProperties()));
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }

    /***
     * MappedStatement构造器接受的是SqlSource
     * 实现SqlSource接口，将BoundSql封装进去
     */
    public static class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }
}
